import { _decorator, Component, Node, RigidBody2D, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('friction')
export class friction extends Component {
    @property(Number)
    public fric: number = 0.15;      // 摩擦力倍数

    private position: Vec2 = null!;        // 上一帧的位置

    onLoad() {
        // 设置物体当前位置为初始位置
        this.position = this.getCurrentPosition();
    }

    start() {

    }

    update(deltaTime: number) {
        // 获取运动方向
        let direction = this.getDirection();
        // 如果物体正在运动，就施加力
        // console.log(direction.toString());
        if (!direction.equals2f(0, 0)) {
            // 得到一个摩擦力的向量（移动方向的反向 * 摩擦倍数）
            let fricForce = direction.clone().negative().multiplyScalar(this.fric);
            // 将摩擦力施加给节点
            let rb = this.node.getComponent(RigidBody2D)!;
            // rb.linearVelocity.add(fricForce);
            rb.linearVelocity = new Vec2(rb.linearVelocity.x + fricForce.x, rb.linearVelocity.y + fricForce.y);
            // this.node.position.add3f(fricForce.x, fricForce.y, 0);
        }
    }

    private static isNumberNear(a: number, b: number, diff: number = 0.0001) {
        return Math.abs(a - b) < diff;
    }

    // 获取节点当前位置
    getCurrentPosition() {
        let currentPosition = this.node.position;
        return new Vec2(currentPosition.x, currentPosition.y);
    }

    // 获取节点运动方向
    getDirection() {
        let currentPosition = this.getCurrentPosition();
        // 当前方向减上一帧方向，即为运动方向
        let direction = currentPosition.clone().subtract(this.position);
        // 这里需要注意精度问题
        if (friction.isNumberNear(direction.x, 0)) {
            direction.x = 0;
        }
        if (friction.isNumberNear(direction.y, 0)) {
            direction.y = 0;
        }

        // 更新位置
        this.position = currentPosition;
        // 返回结果
        return direction;
    }
}


